//
//  SJPhotoBrowserController.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/10/9.
//  Copyright © 2015年 world. All rights reserved.
//
//  图片浏览器   点击cell中的照片 跳转到的界面

import UIKit
import SVProgressHUD

let SJPhotoBrowserReuseIdentifier = "SJPhotoBrowserReuseIdentifier"
class SJPhotoBrowserController: UIViewController {
    
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    func save(){
        //获取浏览器中的图片
        let image = getImageView().image
        
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //返回当前点击的图片
    func getCurrentImageIndex()->Int{
        //indexPathsForVisibleItems 返回NSIndexPath的数组 , 取最后一个indexPath
        //返回indexPath的item
        return collectionView.indexPathsForVisibleItems().last!.item
    }
    //取到图片浏览器中的图片
    func getImageView()-> UIImageView{
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! SJPhotoViewCell
        return cell.imageView
    }
    
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    //照片保存的回调方法
    func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject){
        if error != nil{
            SVProgressHUD.showErrorWithStatus("报错出错")
        }else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    
//    override func viewWillAppear(animated: Bool) {
//        super.viewWillAppear(animated)
//        print(__FUNCTION__+"\(view.frame)+\(collectionView.frame)")
//    }
//    override func viewWillLayoutSubviews() {
//        super.viewWillLayoutSubviews()
//        print(__FUNCTION__+"\(view.frame)+\(collectionView.frame)")
//
//    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
//        print(__FUNCTION__+"\(view.frame)+\(collectionView.frame)")
        parepateLayout()

        let indexPath = NSIndexPath(forItem: photoIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    func parepateLayout(){
        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
    }
    
    override func loadView() {
        var screenFrame = UIScreen.mainScreen().bounds
        screenFrame.size.width += 20.0
        view = UIView(frame: screenFrame)
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        view.backgroundColor = UIColor.blackColor()
        prepareCollectionView()
        
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
    
    }
    
    ///z准备collectionView
    private func prepareCollectionView(){
        collectionView.backgroundColor = UIColor.clearColor()
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(SJPhotoViewCell.self, forCellWithReuseIdentifier: SJPhotoBrowserReuseIdentifier)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

            //print(imageURLs)
    }
    init(imageURLs:[NSURL],photoIndex:Int){
        self.imageURLs = imageURLs
        self.photoIndex = photoIndex
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
 /// 图片url数组
    private var imageURLs:[NSURL]
 /// 图片索引
    private var photoIndex:Int
    
    // MARK: - 懒加载控件
    //
    lazy var layout = UICollectionViewFlowLayout()
    lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    lazy var saveButton: UIButton = UIButton(title: "保存", titleSize: 14)
    lazy var closeButton: UIButton = UIButton(title: "关闭", titleSize: 14)
    
    
    //照片缩放比例,与OC类似,分类中不能写属性
    var photoScale:CGFloat = 1
}

extension SJPhotoBrowserController : UICollectionViewDataSource,SJPhotoViewCellImageDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SJPhotoBrowserReuseIdentifier, forIndexPath: indexPath) as! SJPhotoViewCell
        cell.backgroundColor = UIColor.clearColor()
        //给cell的imageURL赋值
        cell.imageURL = imageURLs[indexPath.item]
        //设置代理
        cell.photoDelegate = self

        return cell
    }
    
    //MARK: -SJPhotoViewCellImageDelegate
    //photo被点击
    func photoViewCellImageDidClick() {
        close()
    }
    //photo进行缩放的时候
    func photoViewDidScale(scale: CGFloat) {
        print(scale)
        //交互式转场
        photoScale = scale
        hidePhotoControl(photoScale < 0.8)
        //当scale<1的时候进行交互转场
        if photoScale < 1.0{
            startInteractiveTransition(self)
        }
    }
    
    //photo完成缩放
    func photoViewDidFinshScale() {
        //告诉转场动画完成
        
        if photoScale < 0.8 {
            completeTransition(true)
        }else{
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
    }
    
    //隐藏控图片浏览器控制器
    private func hidePhotoControl(isHidden:Bool){
        view.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        saveButton.hidden = isHidden
        closeButton.hidden = isHidden
    }
    
}
//MARK: - UIViewControllerInteractiveTransitioning 交互转场动画
extension SJPhotoBrowserController:UIViewControllerInteractiveTransitioning,UIViewControllerContextTransitioning{
    //transitionContext 提供转场动画所需的所以信息
    //需要传入一个遵守了UIViewControllerContextTransitioning协议的对象
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        view.alpha = photoScale
    }
    // 转成动画中,这个函数很重要 告诉转场动画结束
    func completeTransition(didComplete: Bool){
        dismissViewControllerAnimated(true, completion: nil)
    }

    func containerView() -> UIView?{return self.view}

    func isAnimated() -> Bool{return true}
    
    func isInteractive() -> Bool {return true}
    
    func transitionWasCancelled() -> Bool{return true}
    
    func presentationStyle() -> UIModalPresentationStyle{return UIModalPresentationStyle.Custom}
    func updateInteractiveTransition(percentComplete: CGFloat){}
    func finishInteractiveTransition(){}
    func cancelInteractiveTransition(){}
    
    func viewControllerForKey(key: String) -> UIViewController?{return self}
    
    func viewForKey(key: String) -> UIView?{return self.view}
    func targetTransform() -> CGAffineTransform{return CGAffineTransformIdentity}
    func initialFrameForViewController(vc: UIViewController) -> CGRect{return CGRectZero}
    func finalFrameForViewController(vc: UIViewController) -> CGRect{return CGRectZero}

}


// MARK: - UICollectionViewDelegate
extension SJPhotoBrowserController:UICollectionViewDelegate{
    //当collectionView的cell在全屏的时候,不会触发该方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print(__FUNCTION__)
    }
    
    
}
